package ru.dadle8;

import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.methods.commands.SetMyCommands;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.api.objects.commands.BotCommand;
import org.telegram.telegrambots.meta.api.objects.commands.scope.BotCommandScopeDefault;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import ru.dadle8.configuration.BotProperties;
import ru.dadle8.model.bot.type.Action;
import ru.dadle8.service.api.ExecutorFactory;
import ru.dadle8.service.api.MessageExecutor;

import java.util.List;

@Slf4j
@Component
public class Bot extends TelegramLongPollingBot {
    private final static List<BotCommand> LIST_OF_COMMANDS = List.of(
            new BotCommand("/continue", "Продолжить с последнего действия"),
            new BotCommand(Action.TRAINING.getAction(), "Показать список тренировок"),
            new BotCommand(Action.KBJU.getAction(), "Расчет КБЖУ"),
            new BotCommand(Action.GET.getAction(), "Получить мотивирующую цитату от тренера!"),
            new BotCommand(Action.FIND_WORKOUT.getAction(), "Поиск тренировки"),
            new BotCommand(Action.GET_WORKOUTS.getAction(), "Выбрать тренировку"),
            new BotCommand("/help", "Помощь"),
            new BotCommand("/stop", "Остановить")
    );
    private final BotProperties botProperties;
    private final ExecutorFactory executorFactory;

    Bot(BotProperties botProperties, @Lazy ExecutorFactory executorFactory) {
        super(botProperties.token());
        this.botProperties = botProperties;
        this.executorFactory = executorFactory;
    }

    @PostConstruct
    public void setCustomCommands() {
        try {
            execute(new SetMyCommands(LIST_OF_COMMANDS, new BotCommandScopeDefault(), null));
        } catch (TelegramApiException e) {
            log.error(e.getMessage());
        }
    }

    @Override
    public String getBotUsername() {
        return botProperties.username();
    }

    @Override
    public void onUpdateReceived(Update update) {
        try {
            MessageExecutor messageExecutor = executorFactory.getMessageExecutor(update);
            if (messageExecutor != null) {
                messageExecutor.execute(update);
            } else {
                log.info("Что-то не обработано.\n" + update.toString());
            }
        } catch (TelegramApiException e) {
            log.error(e.getMessage());
        }
    }

}
